<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PDF文件转图片</title>
<!--<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>-->
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/pdf.js"></script>
<script type="text/javascript" src="js/pdf.worker.js"></script>
<script type="text/javascript" src="js/jszip.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>
<script type="text/javascript" src="js/LodopFuncs.js"></script>
<style type="text/css">

	button {
		width: 120px;
	 	line-height: height: 30px;
		background: none;
		border: 1px solid #b1afaf;
		border-radius: 5px;
		font-size: 12px;
		font-weight: 1000;
		color: #384240;
		cursor: pointer;
		outline: none;
		margin: 0 0.5%
	}

	button:hover {
		background: #ccc;
	}

	#container {
	    width: 600px;
	    height: 800px;
	    margin: 1% auto;
		border-radius: 2px;
		border: 2px solid #a29b9b;
	}

	.pdfInfos {
		margin: 0 2%;
	}

</style>
</head>

<body>

	<div style="text-align: center;margin-top:1%">						
	    <button id="prevpage">上一页</button>
	    <button id="nextpage">下一页</button>
		<button id="exportImg">导出图片</button>
		<button id="printImg">打印所有图片</button>
		<button id="printCurrentPages">打印当前base64</button>
		<button id="printCurrentPagesPart">打印半张未实现</button>
		<button onclick="choosePdf()">选择一个pdf文件</button>
		<input style="display:none" id='chooseFile' type='file' accept="application/pdf" multiple="multiple">
	</div>

	<div style="text-align: center;margin-top:1%">
		<span class="pdfInfos">页码：<span id="currentPages"></span><span id="totalPages"></span></span>
		<span class="pdfInfos">文件名：<span id="fileName"></span></span>
		<span class="pdfInfos">文件大小：<span id="fileSize"></span></span>
	</div>

	<div style="position: relative;">
		<style type="text/css">
		#pdfList button{ margin-bottom: 10px;}
		#pdfList button.cur{ background: #ccc }
		
		</style>
		<div id="pdfList" style=" position: absolute;left: 19.5%; width: 120px; text-align: center; ">
		</div>
		<div id="container"></div>
		<img id="imgloading" style="position: absolute;top: 20%;left: 34%;display:none" src="loading.gif">
	</div>

</body>


<script>
	// $(function(){
	// 	$("#pdfList").on('click','button',function(){
	// 		$("#pdfList button").removeClass('cur')
	// 		$(this).addClass('cur')
	// 		changePdf($(this).index())
	// 		console.log($(this).index())
	// 	})
	// })
	var filesdataArr=[]
	var currentPages,totalPages,totalPagesTmp //声明一个当前页码及总页数变量
	var scale = 2; //设置缩放比例，越大生成图片越清晰

	currentPages=1; //重置当前页数
	totalPages=0;
	var j=1;


	$('#chooseFile').change(function() {
		var pdfFilePath = $('#chooseFile').val();
		console.log('pdfFilePath',pdfFilePath)
		console.log('chooseFile',$('#chooseFile'))
		if(pdfFilePath) {
			$("#imgloading").css('display','block');
			// $("#container").empty(); //清空上一PDF文件展示图

			// currentPages=1; //重置当前页数
			// totalPages=0; //重置总页数

		    var filesdata = $('#chooseFile')[0].files; //jquery获取到文件 返回属性的值

		    // filesdataArr.push($('#chooseFile')[0])
			var fileSize = filesdata[0].size; //文件大小
			var mb;

			if(fileSize) {
				mb = fileSize / 1048576;
				if(mb > 10) {
					alert("文件大小不能>10M");
					return;
				}
			}

			// $("#pdfList").html()

			$("#fileName").text(filesdata[0].name);
			$("#fileSize").text(mb.toFixed(2) + "Mb");
			 Object.values(filesdata).forEach(o=>{
				$("#pdfList").append('<button>'+o.name+'</button>');

			 	var reader = new FileReader();
				reader.readAsDataURL(o); //将文件读取为 DataURL
				reader.onload = function(e) { //文件读取成功完成时触发

					pdfjsLib.getDocument(this.result).then(function(pdf) { //调用pdf.js获取文件
						if(pdf) {
							totalPages = totalPages+pdf.numPages; //获取pdf文件总页数
							$("#currentPages").text("1/");
							$("#totalPages").text(totalPages);

							//遍历动态创建canvas
							for(var i = 1; i <= pdf.numPages; i++) {
								var canvas = document.createElement('canvas');
								canvas.id = "pageNum" + j;
								$("#container").append(canvas);
								var context = canvas.getContext('2d');
								renderImg(pdf,i,context);
								j++
							}
						}
					});

				};
		    	
		    })

		}
	});

	//渲染生成图片
	function renderImg(pdfFile,pageNumber,canvasContext) {
		pdfFile.getPage(pageNumber).then(function(page) { //逐页解析PDF
			var viewport = page.getViewport(scale); // 页面缩放比例
			var newcanvas = canvasContext.canvas;

			//设置canvas真实宽高
			newcanvas.width = viewport.width;
			newcanvas.height = viewport.height;

			//设置canvas在浏览中宽高
			newcanvas.style.width = "100%";
			newcanvas.style.height = "100%";

			//默认显示第一页，其他页隐藏
			if (pageNumber!=1) {
			   newcanvas.style.display = "none";
			}

			var renderContext = {
				canvasContext: canvasContext,
				viewport: viewport
			};

			page.render(renderContext); //渲染生成
		});

		$("#imgloading").css('display','none');

		return;
	};

	//上一页
	$("#prevpage").click(function(){

        if (!currentPages||currentPages <= 1) {
            return;
        }

		nowpage=currentPages;
        currentPages--;

		$("#currentPages").text(currentPages+"/");

		var prevcanvas = document.getElementById("pageNum"+currentPages);
		var currentcanvas = document.getElementById("pageNum"+nowpage);
		currentcanvas.style.display = "none";
		prevcanvas.style.display = "block";

	})

	//下一页
	$("#nextpage").click(function(){

		if (!currentPages||currentPages>=totalPages) {
			return;
		}

		nowpage=currentPages;
		currentPages++;

		$("#currentPages").text(currentPages+"/");

		var nextcanvas = document.getElementById("pageNum"+currentPages);
		var currentcanvas = document.getElementById("pageNum"+nowpage);
		currentcanvas.style.display = "none";
		nextcanvas.style.display = "block";

	})

	//导出图片
	$("#exportImg").click(function() {

		if (!$('#chooseFile').val()) {
			alert('请先上传pdf文件')
			return false;
		}

		$("#imgloading").css('display','block');

		var zip = new JSZip(); //创建一个JSZip实例
		var images = zip.folder("images"); //创建一个文件夹用来存放图片

		//遍历canvas，将其生成图片放进文件夹images中
		$("canvas").each(function(index, ele) {
			var canvas = document.getElementById("pageNum" + (index + 1));

			//将图片放进文件夹images中
			//参数1为图片名称，参数2为图片数据（格式为base64，需去除base64前缀 data:image/png;base64）
			images.file("photo-" + (index + 1) + ".png", splitBase64(canvas.toDataURL("image/png", 1.0)), {
				base64: true
			});

		})

		//打包下载
		zip.generateAsync({
			type: "blob"
		}).then(function(content) {
			saveAs(content, "picture.zip"); //saveAs依赖的js文件是FileSaver.js
		    $("#imgloading").css('display','none');
		});

	});

	//截取base64前缀
	function splitBase64(dataurl) {
		var arr = dataurl.split(',')
		return arr[1]
	}

	function choosePdf(){
		$("#chooseFile").click()
	}



	$("#printImg").click(function() {

		if (!$('#chooseFile').val()) {
			alert('请先上传pdf文件')
			return false;
		}

		//$("#imgloading").css('display','block');
		
	   $("canvas").each(function(index, ele) {
		var canvas = document.getElementById("pageNum" + (index + 1));
        var dataUrl =  canvas.toDataURL("image/png", 1.0);

        LODOP=getLodop();   
	  	LODOP.PRINT_INIT("");
		LODOP.SET_PRINT_PAGESIZE(1, 0,0,"A5");
		LODOP.SET_PRINT_STYLE("Stretch",2);
		LODOP.ADD_PRINT_IMAGE("0mm","0mm","RightMargin:0mm","BottomMargin:0mm",dataUrl);
		LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS",true);
		var prt = LODOP.PRINT();
		return prt;

		})


	});


	$("#printCurrentPages").click(function() {

		if (!$('#chooseFile').val()) {
			alert('请先上传pdf文件')
			return false;
		}

		var canvas = document.getElementById("pageNum" + currentPages);
		var dataUrl =  canvas.toDataURL("image/png", 1.0);
		alert(dataUrl);
		// console.log(dataUrl);
        LODOP=getLodop();   
	  	LODOP.PRINT_INIT("");
		LODOP.SET_PRINT_PAGESIZE(1, 0, 0,"A4");
		LODOP.SET_PRINT_STYLE("Stretch",2);
		LODOP.ADD_PRINT_IMAGE("0mm","0mm","RightMargin:0mm","BottomMargin:0mm",dataUrl);
		LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS",true);
		var prt = LODOP.PRINT();
		return prt;

	});


	$("#printCurrentPagesPart").click(function() {

		if (!$('#chooseFile').val()) {
			alert('请先上传pdf文件')
			return false;
		}

		var canvas = document.getElementById("pageNum" + currentPages);	
		var dataUrl =  canvas.toDataURL("image/png", 1.0);
		
        LODOP=getLodop();   
	  	LODOP.PRINT_INIT("");
		LODOP.SET_PRINT_PAGESIZE(1, 0, 0,"A4");
		LODOP.SET_PRINT_STYLE("Stretch",2);
		LODOP.ADD_PRINT_IMAGE("0mm","0mm","RightMargin:0mm","BottomMargin:0mm",dataUrl);
		LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS",true);
		var prt = LODOP.PRINT();
		return prt;

	});


</script>
</html>
